package me.flyray.admin.biz;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.util.WebUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * 谷歌默认验证码组件
 *
 * @author TaoYu
 */
@Slf4j
public class GoogleKaptcha implements Kaptcha {

  private DefaultKaptcha kaptcha;

  @Autowired
  private HttpServletRequest request;

  @Autowired
  private HttpServletResponse response;
  public GoogleKaptcha(DefaultKaptcha kaptcha) {
    this.kaptcha = kaptcha;
  }

  @Override
  public String render() {
    response.setDateHeader(HttpHeaders.EXPIRES, 0L);
    response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store, no-cache, must-revalidate");
    response.addHeader(HttpHeaders.CACHE_CONTROL, "post-check=0, pre-check=0");
    response.setHeader(HttpHeaders.PRAGMA, "no-cache");
    response.setContentType("image/jpeg");
    String sessionCode = kaptcha.createText();
    try (ServletOutputStream out = response.getOutputStream()) {
    	/*if(!StringUtils.isEmpty(username)){
    		cacheApi.set(username, sessionCode, 1);
    	}*/
      request.getSession().setAttribute(KAPTCHA_SESSION_KEY, sessionCode);//KAPTCHA_SESSION_DATE
      request.getSession().setAttribute("KAPTCHA_SESSION_DATE", System.currentTimeMillis());
      ImageIO.write(kaptcha.createImage(sessionCode), "jpg", out);
      log.info("最新生成的验证码====={}",sessionCode);
      return sessionCode;
    } catch (IOException e) {
      log.info("获取登录验证码报错");
      //throw new KaptchaRenderException(e);
      return null;
    }
  }

  @Override
  public boolean validate(String code) {
    return validate(code, 60);
  }

  @Override
  public boolean validate(@NonNull String code, long second) {
	log.info("前端请求验证码====={}",code);
    HttpSession httpSession = request.getSession(false);
    String sessionCode;
    log.info("httpSession====={}",httpSession != null);
    log.info("httpSession Code验证码====={}",(String) WebUtils.getSessionAttribute(request, KAPTCHA_SESSION_KEY));;
    if (httpSession != null && (sessionCode = (String) WebUtils.getSessionAttribute(request, KAPTCHA_SESSION_KEY)) != null) {
      log.info("sessionCode验证码====={}",sessionCode);
      if (sessionCode.equalsIgnoreCase(code)) {
        long sessionTime = (long) httpSession.getAttribute("KAPTCHA_SESSION_DATE");
        long duration = (System.currentTimeMillis() - sessionTime) / 1000;
        if (duration < second) {
          httpSession.removeAttribute(KAPTCHA_SESSION_KEY);
          httpSession.removeAttribute("KAPTCHA_SESSION_DATE");
          return true;
        } else {
          //已失效
          return false;
         // throw new KaptchaTimeoutException();
        }
      } else {
    	  //不正确
    	  return false;
        //throw new KaptchaIncorrectException();
      }
    } else {
    	//不存在
    	return false;
      //throw new KaptchaNotFoundException();
    }
  }

}

